import axios from 'axios'
import { Toast } from 'vant'
import store from '@/store/index.js'
// 创建副本
const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})

// 拦截器
_axios.interceptors.request.use(
  config => {
    // 接口有2种方式
    // 不需要token的接口加了就报错
    // 不需要token的接口加不加都正常
    if (!config.noToken) {
      // config.headers.Authorization = `Bear ${store.state.user.token}`
      // config.headers.Authorization = `Bear ${store.getters.token}`
      config.headers.Authorization = `Bear ${store.getters['user/getToken']}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

_axios.interceptors.response.use(
  res => {
    return res.data
  },
  error => {
    console.dir(error)
    if (error.response.data && error.response.data.message) {
      Toast.fail(error.response.data.message)
    }
    return Promise.reject(error)
  }
)

export default _axios
